<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>webpack4升级篇 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="webpack,升级,">
  

  <meta name="description" content="一、环境及依赖库更新 由于Webpack的更新，很多Loader也必须更新才能适应Webpack的最新版本     必须更新的loader 最低要求版本 功能说明     babel-loader 7.1.3 对最新的ES语法进行转换   eslint-loader 2.0.0 代码检查   file-loader 1.1.10 批量修改文件路径，或者指定编译后文件存储路径   vue-loade">
<meta name="keywords" content="webpack,升级">
<meta property="og:type" content="article">
<meta property="og:title" content="webpack4升级篇">
<meta property="og:url" content="http://blog.poetries.top/2018/11/25/webpack4-update/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、环境及依赖库更新 由于Webpack的更新，很多Loader也必须更新才能适应Webpack的最新版本     必须更新的loader 最低要求版本 功能说明     babel-loader 7.1.3 对最新的ES语法进行转换   eslint-loader 2.0.0 代码检查   file-loader 1.1.10 批量修改文件路径，或者指定编译后文件存储路径   vue-loade">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="webpack4升级篇">
<meta name="twitter:description" content="一、环境及依赖库更新 由于Webpack的更新，很多Loader也必须更新才能适应Webpack的最新版本     必须更新的loader 最低要求版本 功能说明     babel-loader 7.1.3 对最新的ES语法进行转换   eslint-loader 2.0.0 代码检查   file-loader 1.1.10 批量修改文件路径，或者指定编译后文件存储路径   vue-loade">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、环境及依赖库更新"><span class="toc-text">一、环境及依赖库更新</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、Webpack-4-x-的破坏性变更"><span class="toc-text">二、Webpack 4.x 的破坏性变更</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-使用config-optimization代替"><span class="toc-text">2.1 使用config.optimization代替</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-压缩JS及CSS文件"><span class="toc-text">2.2 压缩JS及CSS文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-分离JS文件"><span class="toc-text">2.3 分离JS文件</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3-1-公共代码抽取"><span class="toc-text">2.3.1 公共代码抽取</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-提取CSS到单独文件"><span class="toc-text">2.4 提取CSS到单独文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-用更加快捷的mode模式来优化配置文件"><span class="toc-text">2.5 用更加快捷的mode模式来优化配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6-其他调整项备忘"><span class="toc-text">2.6 其他调整项备忘</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、更多参考"><span class="toc-text">三、更多参考</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-webpack4-update" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">webpack4升级篇</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.11.25</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.8k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、环境及依赖库更新"><a href="#一、环境及依赖库更新" class="headerlink" title="一、环境及依赖库更新"></a>一、环境及依赖库更新</h2><blockquote>
<p>由于<code>Webpack</code>的更新，很多<code>Loader</code>也必须更新才能适应<code>Webpack</code>的最新版本</p>
</blockquote>
<table>
<thead>
<tr>
<th>必须更新的loader</th>
<th>最低要求版本</th>
<th>功能说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>babel-loader</code></td>
<td><code>7.1.3</code></td>
<td>对最新的ES语法进行转换</td>
</tr>
<tr>
<td><code>eslint-loader</code></td>
<td><code>2.0.0</code></td>
<td>代码检查</td>
</tr>
<tr>
<td><code>file-loader</code></td>
<td><code>1.1.10</code></td>
<td>批量修改文件路径，或者指定编译后文件存储路径</td>
</tr>
<tr>
<td><code>vue-loader</code></td>
<td><code>15.0.0</code></td>
<td>解析、编译<code>vue</code>单文件组件</td>
</tr>
<tr>
<td><code>vue-style-loader</code></td>
<td><code>4.1.0</code></td>
<td>解析、编译<code>vue</code>单文件组件中的样式</td>
</tr>
</tbody>
</table>
<h2 id="二、Webpack-4-x-的破坏性变更"><a href="#二、Webpack-4-x-的破坏性变更" class="headerlink" title="二、Webpack 4.x 的破坏性变更"></a>二、Webpack 4.x 的破坏性变更</h2><blockquote>
<p>由于<code>Webpack 4.x</code>的重大变更，导致其不再支持部分插件和<code>Loader</code>，其中最闹心的是<code>Chunk</code>分离及文件分离</p>
</blockquote>
<table>
<thead>
<tr>
<th>失效的插件或loader</th>
<th>类型</th>
<th>功能说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>webpack.optimize.CommonsChunkPlugin</code></td>
<td>内置插件</td>
<td>分离<code>Chunk</code>。将多次出现的代码统一打包到一个文件中。<code>Vue</code>工程中用来打包<code>vendor</code>及<code>mainfest</code></td>
</tr>
<tr>
<td><code>webpack.optimize.UglifyJsPlugin</code></td>
<td>内置插件</td>
<td>压缩JS</td>
</tr>
<tr>
<td><code>extract-text-webpack-plugin</code></td>
<td><code>Loader</code></td>
<td>分离文件。将部分代码或文件提取到单独文件中。Vue工程里用来分离CSS到指定文件</td>
</tr>
</tbody>
</table>
<h3 id="2-1-使用config-optimization代替"><a href="#2-1-使用config-optimization代替" class="headerlink" title="2.1 使用config.optimization代替"></a>2.1 使用config.optimization代替</h3><blockquote>
<p>在<code>Webpack 4.x</code>中，新增了<code>optimization</code>的选项来代替之前版本中的<code>webpack.optimize</code>等。在<code>optimization</code>选项中，我们可以进行详细的设置，以达到分离<code>CSS</code>，分离<code>Chunk</code>，压缩文件等等操作</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    optimization: &#123;&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="2-2-压缩JS及CSS文件"><a href="#2-2-压缩JS及CSS文件" class="headerlink" title="2.2 压缩JS及CSS文件"></a>2.2 压缩JS及CSS文件</h3><blockquote>
<p>由于<code>Webpack 4.x</code>中取消了其内置插件，所以之前的方法都不管用了。这里我推荐大家使用<code>UglifyJsPlugin</code>及<code>OptimizeCSSPlugin</code>插件来代替之前的内置插件，当然如果你只是想简单的压缩，而不做任何配置的话，可以按照官方文档中给出的方法使用<code>optimization.minimizer: true</code>即可</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> UglifyJsPlugin = <span class="built_in">require</span>(<span class="string">"uglifyjs-webpack-plugin"</span>)</span><br><span class="line"><span class="keyword">const</span> OptimizeCSSPlugin = <span class="built_in">require</span>(<span class="string">'optimize-css-assets-webpack-plugin'</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    optimization: &#123;</span><br><span class="line">        minimizer: [</span><br><span class="line">            <span class="comment">// js mini</span></span><br><span class="line">            <span class="keyword">new</span> UglifyJsPlugin(&#123;</span><br><span class="line">              cache: <span class="literal">true</span>,</span><br><span class="line">              parallel: <span class="literal">true</span>,</span><br><span class="line">              sourceMap: <span class="literal">false</span> <span class="comment">// set to true if you want JS source maps</span></span><br><span class="line">            &#125;),</span><br><span class="line">            <span class="comment">// css mini</span></span><br><span class="line">            <span class="keyword">new</span> OptimizeCSSPlugin(&#123;&#125;)</span><br><span class="line">        ]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-3-分离JS文件"><a href="#2-3-分离JS文件" class="headerlink" title="2.3 分离JS文件"></a>2.3 分离JS文件</h3><blockquote>
<p>在之前版本中，我们使用<code>CommonsChunkPlugin</code>进行文件分离，而在<code>Webpack 4.x</code>中，我们则借助于<code>config.optimization</code>来实现</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// webpack 3.xx</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    plugins:[</span><br><span class="line">         <span class="keyword">new</span> webpack.optimize.CommonsChunkPlugin(&#123;</span><br><span class="line">            name: <span class="string">'vendor'</span>,</span><br><span class="line">            minChunks: <span class="function"><span class="keyword">function</span>(<span class="params">module</span>) </span>&#123;</span><br><span class="line">                <span class="comment">// any required modules inside node_modules are extracted to vendor</span></span><br><span class="line">                <span class="keyword">return</span> (</span><br><span class="line">                    <span class="built_in">module</span>.resource &amp;&amp;</span><br><span class="line">                    /\.js$/.test(<span class="built_in">module</span>.resource) &amp;&amp;</span><br><span class="line">                    <span class="built_in">module</span>.resource.indexOf(</span><br><span class="line">                        path.join(__dirname, <span class="string">'../node_modules'</span>)</span><br><span class="line">                    ) === <span class="number">0</span></span><br><span class="line">                )</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;),</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// webpack4</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    optimization: &#123;</span><br><span class="line">        splitChunks: &#123;</span><br><span class="line">            chunks: <span class="string">'async'</span>,</span><br><span class="line">            <span class="comment">// 大于30KB才单独分离成chunk</span></span><br><span class="line">            minSize: <span class="number">30000</span>,</span><br><span class="line">            maxAsyncRequests: <span class="number">5</span>,</span><br><span class="line">            maxInitialRequests: <span class="number">3</span>,</span><br><span class="line">            name: <span class="literal">true</span>,</span><br><span class="line">            cacheGroups: &#123;</span><br><span class="line">                <span class="keyword">default</span>: &#123;</span><br><span class="line">                    priority: <span class="number">-20</span>,</span><br><span class="line">                    reuseExistingChunk: <span class="literal">true</span>,</span><br><span class="line">                &#125;,</span><br><span class="line">                vendors: &#123;</span><br><span class="line">                    name: <span class="string">'vendors'</span>,</span><br><span class="line">                    test: <span class="regexp">/[\\/]node_modules[\\/]/</span>,</span><br><span class="line">                    priority: <span class="number">-10</span>,</span><br><span class="line">                    chunks: <span class="string">"all"</span></span><br><span class="line">                &#125;,</span><br><span class="line">                echarts: &#123;</span><br><span class="line">                    name: <span class="string">'echarts'</span>,</span><br><span class="line">                    chunks: <span class="string">'all'</span>,</span><br><span class="line">                    <span class="comment">// 对echarts进行单独优化，优先级较高</span></span><br><span class="line">                    priority: <span class="number">20</span>,</span><br><span class="line">                    test: <span class="function"><span class="keyword">function</span>(<span class="params">module</span>)</span>&#123;</span><br><span class="line">                        <span class="keyword">var</span> context = <span class="built_in">module</span>.context;</span><br><span class="line">                        <span class="keyword">return</span> context &amp;&amp; (context.indexOf(<span class="string">'echarts'</span>) &gt;= <span class="number">0</span> || context.indexOf(<span class="string">'zrender'</span>) &gt;= <span class="number">0</span>)</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-3-1-公共代码抽取"><a href="#2-3-1-公共代码抽取" class="headerlink" title="2.3.1 公共代码抽取"></a>2.3.1 公共代码抽取</h4><blockquote>
<p><code>CommonsChunkPlugin</code> 已弃用，使用<code>optimization.splitChunks</code>代替</p>
</blockquote>
<p><strong>配置项</strong></p>
<ul>
<li><code>cacheGroups</code> 自定义配置主要使用它来决定生成的文件</li>
<li><code>test</code> 限制范围，可以是正则，匹配文件夹或文件</li>
<li><code>name</code> 生成文件名</li>
<li><code>priority</code> 优先级，多个分组冲突时决定把代码放在哪块</li>
<li><code>minSize</code> 最小尺寸必须大于此值，默认<code>30000B</code></li>
<li><code>minChunks</code> 其他<code>entry</code>引用次数大于此值，默认1(<code>minChunks</code>指的是被不同<code>entry</code>引入的次数)<ul>
<li>为<code>1</code>时，适合分离 <code>node_moudles</code> 里的第三方库（很多人认为这个值设成2其实不合理）</li>
</ul>
</li>
<li>maxInitialRequests entry文件请求的chunks不应该超过此值（请求过多，耗时）</li>
<li>maxAsyncRequests 异步请求的chunks不应该超过此值</li>
<li>automaticNameDelimiter 自动命名连接符</li>
<li><code>chunks</code> 值为<code>&quot;initial&quot;</code>, <code>&quot;async&quot;</code>（默认） 或 <code>&quot;all&quot;</code><ul>
<li><code>initial</code> 入口<code>chunk</code>，对于异步导入的文件不处理</li>
<li><code>async</code> 异步<code>chunk</code>，只对异步导入的文件处理（个人理解）</li>
<li><code>all</code> 全部<code>chunk</code>（我反正选<code>all</code>，不甚理解）</li>
</ul>
</li>
</ul>
<p><strong>使用方式</strong></p>
<ol>
<li>使用默认配置</li>
</ol>
<blockquote>
<p>不配置时再<code>production</code>模式下开启<code>async</code></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">optimization:&#123;</span><br><span class="line">    splitChunks:&#123;</span><br><span class="line">        chunks:<span class="string">"all"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>生成的文件 <code>vendors~xx.js</code> ，xx与入口名对应</p>
</blockquote>
<p>默认配置</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">optimization: &#123;</span><br><span class="line">    splitChunks: &#123;</span><br><span class="line">        chunks: <span class="string">"async"</span>,</span><br><span class="line">        minSize: <span class="number">30000</span>,</span><br><span class="line">        minChunks: <span class="number">1</span>,</span><br><span class="line">        maxAsyncRequests: <span class="number">5</span>,</span><br><span class="line">        maxInitialRequests: <span class="number">3</span>,</span><br><span class="line">        automaticNameDelimiter: <span class="string">'~'</span>,</span><br><span class="line">        name: <span class="literal">true</span>,</span><br><span class="line">        cacheGroups: &#123;</span><br><span class="line">            vendors: &#123;</span><br><span class="line">                test: <span class="regexp">/[\\/]node_modules[\\/]/</span>,</span><br><span class="line">                priority: <span class="number">-10</span></span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="keyword">default</span>: &#123;<span class="comment">//cacheGroups重写继承配置，设为false不继承</span></span><br><span class="line">                minChunks: <span class="number">2</span>,</span><br><span class="line">                priority: <span class="number">-20</span>,</span><br><span class="line">                reuseExistingChunk: <span class="literal">true</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>自定义配置</li>
</ol>
<blockquote>
<p>生成的文件 <code>xx.js</code> ，<code>xx</code>指<code>name</code>的值</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">optimization: &#123;</span><br><span class="line">    <span class="comment">//打包 第三方库</span></span><br><span class="line">    <span class="comment">//打包 公共文件</span></span><br><span class="line">    splitChunks: &#123;</span><br><span class="line">        cacheGroups: &#123;</span><br><span class="line">            vendor:&#123;<span class="comment">//node_modules内的依赖库</span></span><br><span class="line">                chunks:<span class="string">"all"</span>,</span><br><span class="line">                test: <span class="regexp">/[\\/]node_modules[\\/]/</span>,</span><br><span class="line">                name:<span class="string">"vendor"</span>,</span><br><span class="line">                minChunks: <span class="number">1</span>, <span class="comment">//被不同entry引用次数(import),1次的话没必要提取</span></span><br><span class="line">                maxInitialRequests: <span class="number">5</span>,</span><br><span class="line">                minSize: <span class="number">0</span>,</span><br><span class="line">                priority:<span class="number">100</span>,</span><br><span class="line">                <span class="comment">// enforce: true?</span></span><br><span class="line">            &#125;,</span><br><span class="line">            common: &#123;<span class="comment">// ‘src/js’ 下的js文件</span></span><br><span class="line">                chunks:<span class="string">"all"</span>,</span><br><span class="line">                test:<span class="regexp">/[\\/]src[\\/]js[\\/]/</span>,<span class="comment">//也可以值文件/[\\/]src[\\/]js[\\/].*\.js/,  </span></span><br><span class="line">                name: <span class="string">"common"</span>, <span class="comment">//生成文件名，依据output规则</span></span><br><span class="line">                minChunks: <span class="number">2</span>,</span><br><span class="line">                maxInitialRequests: <span class="number">5</span>,</span><br><span class="line">                minSize: <span class="number">0</span>,</span><br><span class="line">                priority:<span class="number">1</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>配合 runtimeChunk</strong></p>
<blockquote>
<p><code>runtimeChunk</code>，将入口提取出来，这样入口文件可以很快加载，并且当哪里有改动的时候，只有改动的地方和这个文件有变化。<br><code>optimization.runtimeChunk</code> 用来提取 <code>entry</code> <code>chunk</code>中的 <code>runtime</code>部分函数，形成一个单独的文件，这部分文件不经常变换，方便做缓存</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">runtimeChunk: &#123;</span><br><span class="line">  name: <span class="string">'manifest'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-4-提取CSS到单独文件"><a href="#2-4-提取CSS到单独文件" class="headerlink" title="2.4 提取CSS到单独文件"></a>2.4 提取CSS到单独文件</h3><blockquote>
<p>在之前版本中我们使用<code>extract-text-webpack-plugin</code>来提取<code>CSS</code>文件，不过在<code>webpack 4.x</code>中则应该使用<code>mini-css-extract-plugin</code>来提取<code>CSS</code>到单独文件中</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// webpack 3.xx</span></span><br><span class="line"><span class="keyword">const</span> utils = <span class="built_in">require</span>(<span class="string">'./utils'</span>)</span><br><span class="line"><span class="keyword">const</span> ExtractTextPlugin = <span class="built_in">require</span>(<span class="string">'extract-text-webpack-plugin'</span>)</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    <span class="keyword">new</span> ExtractTextPlugin(&#123;</span><br><span class="line">        filename: utils.assetsPath(<span class="string">'css/[name].[contenthash:7].css'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// webpack 4.xx</span></span><br><span class="line"><span class="keyword">const</span> utils = <span class="built_in">require</span>(<span class="string">'./utils'</span>)</span><br><span class="line"><span class="keyword">const</span> MiniCssExtractPlugin = <span class="built_in">require</span>(<span class="string">'mini-css-extract-plugin'</span>)</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    <span class="keyword">new</span> MiniCssExtractPlugin(&#123;</span><br><span class="line">        filename: utils.assetsPath(<span class="string">'css/[name].[contenthash:7].css'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// webpack4 生产环境下的配置优化</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> UglifyJsPlugin = <span class="built_in">require</span>(<span class="string">"uglifyjs-webpack-plugin"</span>);</span><br><span class="line"><span class="keyword">const</span> MiniCssExtractPlugin = <span class="built_in">require</span>(<span class="string">"mini-css-extract-plugin"</span>);</span><br><span class="line"><span class="keyword">const</span> OptimizeCSSAssetsPlugin = <span class="built_in">require</span>(<span class="string">"optimize-css-assets-webpack-plugin"</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  optimization: &#123;</span><br><span class="line">    minimizer: [</span><br><span class="line">      <span class="keyword">new</span> UglifyJsPlugin(&#123;</span><br><span class="line">        cache: <span class="literal">true</span>,</span><br><span class="line">        parallel: <span class="literal">true</span>,</span><br><span class="line">        sourceMap: <span class="literal">true</span> </span><br><span class="line">      &#125;),</span><br><span class="line">      <span class="keyword">new</span> OptimizeCSSAssetsPlugin(&#123;&#125;)  <span class="comment">// use OptimizeCSSAssetsPlugin</span></span><br><span class="line">    ]</span><br><span class="line">  &#125;,</span><br><span class="line">  plugins: [</span><br><span class="line">    <span class="keyword">new</span> MiniCssExtractPlugin(&#123;</span><br><span class="line">      filename: <span class="string">'css/app.[name].css'</span>,</span><br><span class="line">      chunkFilename: <span class="string">'css/app.[contenthash:12].css'</span>  <span class="comment">// use contenthash *</span></span><br><span class="line">    &#125;)</span><br><span class="line">  ]</span><br><span class="line">  ....</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>将多个css chunk合并成一个css文件</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> MiniCssExtractPlugin = <span class="built_in">require</span>(<span class="string">"mini-css-extract-plugin"</span>);</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  optimization: &#123;</span><br><span class="line">    splitChunks: &#123;</span><br><span class="line">      cacheGroups: &#123;</span><br><span class="line">        styles: &#123;            </span><br><span class="line">          name: <span class="string">'styles'</span>,</span><br><span class="line">          test: <span class="regexp">/\.scss|css$/</span>,</span><br><span class="line">          chunks: <span class="string">'all'</span>,    <span class="comment">// merge all the css chunk to one file</span></span><br><span class="line">          enforce: <span class="literal">true</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-5-用更加快捷的mode模式来优化配置文件"><a href="#2-5-用更加快捷的mode模式来优化配置文件" class="headerlink" title="2.5 用更加快捷的mode模式来优化配置文件"></a>2.5 用更加快捷的mode模式来优化配置文件</h3><blockquote>
<p><code>webpack4</code>中提供的<code>mode</code>有两个值：<code>development</code>和<code>production</code>，默认值是 <code>production</code>。<code>mode</code>是我们为减小生产环境构建体积以及节约开发环境的构建时间提供的一种优化方案，提供对应的构建参数项的默认开启或关闭，降低配置成本</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 开启方式 1：直接在启动命令后加入参数</span></span><br><span class="line"></span><br><span class="line"><span class="string">"scripts"</span>: &#123;</span><br><span class="line">  <span class="string">"dev"</span>: <span class="string">"webpack --mode development"</span>,</span><br><span class="line">  <span class="string">"build"</span>: <span class="string">"webpack --mode production"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 开启方式 2：可以在配置文件中加入一个mode属性：</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  mode: <span class="string">'production'</span> <span class="comment">// development</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="2-6-其他调整项备忘"><a href="#2-6-其他调整项备忘" class="headerlink" title="2.6 其他调整项备忘"></a>2.6 其他调整项备忘</h3><ul>
<li><code>NoEmitOnErrorsPlugin</code>- &gt; <code>optimization.noEmitOnErrors</code>（默认情况下处于生产模式）</li>
<li><code>ModuleConcatenationPlugin- &gt;</code>optimization.concatenateModules`（默认情况下处于生产模式）</li>
<li><code>NamedModulesPlugin</code>- &gt; <code>optimization.namedModules</code>（在开发模式下默认开启）</li>
<li><code>webpack</code>命令优化 -&gt; 发布了独立的 <code>webpack-cli</code> 命令行工具包</li>
<li><code>webpack-dev-server</code>-&gt; 建议升级到最新版本</li>
<li><code>html-webpack-plugin</code> -&gt; 建议升级到的最新版本</li>
<li><code>file-loader</code> -&gt; 建议升级到最新版本</li>
<li><code>url-loader</code> -&gt; 建议升级到最新版本</li>
</ul>
<h2 id="三、更多参考"><a href="#三、更多参考" class="headerlink" title="三、更多参考"></a>三、更多参考</h2><ul>
<li><a href="https://github.com/GoogleChromeLabs/webpack-libs-optimizations" target="_blank" rel="noopener">一些优化wepback的库</a></li>
<li><a href="http://blog.poetries.top/2018/11/18/webpack4-config/">webpack4配置详解</a></li>
<li><a href="https://segmentfault.com/a/1190000015592264" target="_blank" rel="noopener">webpack4.x配置指南</a></li>
<li><a href="https://segmentfault.com/a/1190000015970277" target="_blank" rel="noopener">webpack4 化繁为简（二)</a></li>
<li><a href="https://www.cnblogs.com/carrotWu/p/8665720.html" target="_blank" rel="noopener">记一次webpack3升级webpack4的踩坑</a></li>
<li><a href="https://segmentfault.com/a/1190000015263836" target="_blank" rel="noopener">webpack4.0让编译速度飙升</a></li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/11/23/webpack-dll/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/11/26/docker-pm2-deploy-node-proj/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
